package com.zhao.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.Util.MD5_Shiro;
import com.zhao.mapper.FollowMapper;
import com.zhao.mapper.UserMapper;
import com.zhao.pojo.*;
import com.zhao.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    FollowMapper followMapper;
    @Autowired
    ArticleService articleService;
    @Autowired
    WalletService walletService;
    @Autowired
    DatafileService datafileService;
    @Autowired
    StatisticService statisticService;
    @Autowired
    CommentService commentService;
    @Autowired
    FileCommentService fileCommentService;
    @Autowired
    FileStatisticService fileStatisticService;


    @Override
    public void saveOrUpdateUser(User user) {
        if (user.getUserId() == null) {
            this.addUser(user);
            userMapper.saveRoles(user.getRids());
        } else {
            userMapper.delUserRole(user.getUserId());

            User byId = userMapper.selectById(user.getUserId());
            String newPwd = MD5_Shiro.encryptPassword("MD5",user.getUserPass(),byId.getSalt(),1024);
            user.setUserPass(newPwd);
            userMapper.updateById(user);
            userMapper.updateRoles(user.getUserId(), user.getRids());
        }
    }
    /***
    * @Description: 删除用户，的前提是删除用户所有的其他信息
    * @Param: [id] 用户id
    * @return: void
    * @Author: Mr.zhao
    * @Date: 2021/10/6
    */
    @Override
    public void delUser(Integer id) {
        //获取用户名
        String account = userMapper.selectById(id).getUserAccount();
        //获取全部文章id
        List<Article> articles = articleService.list(new QueryWrapper<Article>().eq("author", account));
        //删除全部文章统计
        //删除文章评论
        //删除文章
        for (Article article : articles) {
            statisticService.remove(new QueryWrapper<Statistic>().eq("article_id",article.getArticleId()));
            commentService.remove(new QueryWrapper<Comment>().eq("article_id",article.getArticleId()));
            articleService.removeById(article.getArticleId());
        }
        //获取全部资源
        List<Datafile> datafiles = datafileService.list(new QueryWrapper<Datafile>().eq("author", account));
        //删除全部资源评论
        //删除资源
        //删除资源统计
        for (Datafile datafile : datafiles) {
            fileStatisticService.remove(new QueryWrapper<Filestatistic>().eq("file_id",datafile.getFileId()));
            fileCommentService.remove(new QueryWrapper<FileComment>().eq("file_id",datafile.getFileId()));
            datafileService.removeById(datafile.getFileId());
        }
        //删除钱包
        walletService.remove(new QueryWrapper<Wallet>().eq("uid",id));
        userMapper.delUserRole(id);
        userMapper.deleteById(id);
    }

    @Override
    public List<String> checked(Integer id) {
        return userMapper.checked(id);
    }

    @Override
    public List<String> getByIdPerms(Integer userId) {
        return userMapper.getByIdPerms(userId);
    }

    //md5加密注册
    @Override
    public String addUser(User user) {
        //查询注册的用户名，在数据库中是否存在，如果查询到的信息为空，则注册添加用户信息
        //查询用户
        User info = userMapper.selectOne(new QueryWrapper<User>().eq("user_name", user.getUserName()));
        //查询注册的昵称，在数据库中是否存在
        User byNickName = userMapper.selectOne(new QueryWrapper<User>().eq("user_account", user.getUserAccount()));
        if (info != null) {
            return "134";//用户名存在
        } else if (byNickName != null) {
            return "135";//笔名存在
        } else {
            try {
                //随机生成UUID，作为盐值
                String uuid = UUID.randomUUID().toString().replace("-", "");
                //调用MD5_Shiro工具类，生成加密后的密码
                String newPwd = MD5_Shiro.encryptPassword("MD5", user.getUserPass(), uuid, 1024);
                user.setUserPass(newPwd);
                user.setSalt(uuid);
                userMapper.insert(user);
                return "200";//正常
            } catch (Exception e) {
                e.printStackTrace();
                return "502";//异常
            }
        }
    }

    //注册时 分配默认角色 普通用户
    @Override
    public void registerUserRole(Integer userId, int roleid) {
        userMapper.registerUserRole(userId, roleid);
    }

    @Override
    public List<Comment> ListNewcomment(String userAccount) {
        return userMapper.ListNewcomment(userAccount);
    }

    @Override
    public List<Article> ListhotsArticle(int i, String account) {
        return userMapper.ListhotsArticle(i, account);
    }

    @Override
    public Statistic SumStatistic(String userAccount) {
        return userMapper.SumStatistic(userAccount);
    }
    //关注
    @Override
    public void saveorUpdateFollow(Integer userId, Integer fid, String iffollow) {
        if (iffollow.equals("no")){
            Follow follow = new Follow();
            follow.setUid(userId);
            follow.setFid(fid);
            followMapper.insert(follow);
        }else {
            followMapper.delete(new QueryWrapper<Follow>().eq("uid",userId).eq("fid",fid));
        }
    }

    @Override
    public String updateUserInfoAll(User user, String res,String value) {
        if (res.equals("2")){//修改手机号
            user.setUserIphone(value);
        }else if (res.equals("3")){//修改邮箱
            user.setUserEmail(value);
        }else if (res.equals("4")){//注销
            user.setStatus("注销");
        }
        userMapper.updateById(user);
        return "1";
    }

}
